package com.example.demo.controller;

import com.example.demo.model.NewsInfo;
import com.example.demo.service.NewsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsInfoService newsInfoService;

    @RequestMapping("/queryNewsInfoById")
    public NewsInfo queryNewsInfoById(Integer id) {
        log.info("查询新闻信息：" + id);
        return newsInfoService.queryNewsInfoById(id);
    }

    @RequestMapping("/getNewsList")
    public List<NewsInfo> getNewsList() {
        return (List<NewsInfo>) newsInfoService.getNewsList();
    }
@RequestMapping("/getNewsText")
    public NewsInfo getNewsText(Integer id){
        log.info("新闻内容："+id);
        return newsInfoService.getNewsText(id);
    }
    @RequestMapping("/addNews")
    public String addNews(NewsInfo newsInfo){
        log.info("添加新闻信息："+newsInfo);
        if(!StringUtils.hasLength(newsInfo.getTitle())
        ||!StringUtils.hasLength(newsInfo.getAuthor())
                ||newsInfo.getNewsDate()==null
                ||newsInfo.getHeat()==null
        ){
            log.info("添加新闻，参数不合法，request："+newsInfo);
            return "参数不合法";
        }
        try {
            newsInfoService.addNews(newsInfo);
            return "";
        }catch (Exception e){
            log.info("添加新闻异常，e："+e);
            return "添加新闻有异常";
        }
    }

    @RequestMapping("/deleteNews")
    public String deleteNews(Integer id){
        log.info("删除新闻：deleteNews"+id);
        try{
            NewsInfo newsInfo=new NewsInfo();
            newsInfo.setId(id);
            newsInfo.setStatusCode(0);
            newsInfoService.updateNews(newsInfo);
            return "";
        }catch (Exception e){
            log.info("异常"+e);
            return "有异常联系管理员";
        }
    }

    @RequestMapping("/updateNews")
    public String updateNews(NewsInfo newsInfo){
        log.info("修改新闻信息："+newsInfo);
        try{
            newsInfoService.updateNews(newsInfo);
            return "";
        } catch (Exception e){
            log.info("异常："+e);
            return "有异常联系管理员";
        }
    }

    @RequestMapping("/batchDelete")
    public String batchDelete(@RequestParam List<Integer> ids){
        log.info("批量删除新闻 ids:"+ids);
        try{
            newsInfoService.batchDelete(ids);
            return "";
        }catch (Exception e){
            log.info("异常e:",e);
            return "异常";
        }
    }
}

